package com.salt.modules.sys.service;

import com.salt.common.json.AjaxJson;
import com.salt.common.service.CrudService;
import com.salt.common.utils.StringUtils;
import com.salt.modules.sys.entity.UserAppDevice;
import com.salt.modules.sys.mapper.UserAppDeviceMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Date;

/**
 * @Description
 * @Author salt
 * @Date 2022/12/29
 * @Version 1.0.1
 */
@Service
@Transactional(readOnly = true)
public class UserAppDeviceService extends CrudService<UserAppDeviceMapper, UserAppDevice> {

    public UserAppDevice find(String userId){
        return mapper.find(userId);
    }

    @Transactional(readOnly = false)
    public AjaxJson saveDevice(@RequestParam("uid") String uid,
                               @RequestParam("aid") String aid,
                               @RequestParam("code") Integer code) {
        if (StringUtils.isNotBlank(uid) &&
                StringUtils.isNotBlank(aid) &&
                code != null) {
            UserAppDevice device = mapper.find(uid);
            UserAppDevice userAppDevice = new UserAppDevice();
            userAppDevice.setUserId(uid);
            userAppDevice.setDeviceId(aid);
            userAppDevice.setFreeCode(code);
            userAppDevice.setUpdateDate(new Date());
            if (device != null) {
                mapper.updateFreeCode(userAppDevice);
            } else {
                userAppDevice.setCreateDate(userAppDevice.getUpdateDate());
                mapper.insert(userAppDevice);
            }
            return AjaxJson.success("保存成功!");
        }
        return AjaxJson.error("保存失败!");
    }

    @Transactional(readOnly = false)
    public void updateDeviceId(UserAppDevice userAppDevice){
        userAppDevice.setUpdateDate(new Date());
        mapper.updateDeviceId(userAppDevice);
    }

    @Transactional(readOnly = false)
    public void updateFreeCode(UserAppDevice userAppDevice){
        userAppDevice.setUpdateDate(new Date());
        mapper.updateFreeCode(userAppDevice);
    }
}
